#!/bin/bash

INPUT_FILE=
GROUP_NAME=

function usage() {
    echo "Usage: $0 -i <input_file> -g <group_name>"
}

while getopts "i:g:" opt; do
    case $opt in
    i)
        INPUT_FILE=$OPTARG
        ;;
    g)
        GROUP_NAME=$OPTARG
        ;;
    ?)
        usage
        exit 0
        ;;
    esac
done

if [[ -z "$INPUT_FILE" || -z "$GROUP_NAME" ]]; then
    usage
    exit 1
fi

CAT=cat
case $INPUT_FILE in
    *.bz2) CAT=bzcat;;
    *.gz)  CAT=gzcat;;
    *.xz)  CAT=xzcat;;
esac

FIFO=`mktemp -u -t usenet-indexer`

mkfifo $FIFO
if [ $? -ne 0 ]; then
    echo "Could not create FIFO: $FIFO"
    exit 1
fi

$CAT $INPUT_FILE > $FIFO &
curl \
    "http://localhost:8080/usenet-indexer/update/csv?separator=%09&encapsulator=%08" \
    -F header=false \
    -F fieldnames=article_id,lines,bytes,date,subject,message_id,author \
    -F overwrite=false \
    -F commit=true \
    -F stream.file=$FIFO \
    -F literal.group_name=$GROUP_NAME

if [ $? -ne 0 ]; then
    echo "There was an error processing file $INPUT_FILE"
    rm $FIFO
    exit 1
fi

wait
rm $FIFO
